package org.fuxia.im.core.utils;

/**
 * byte工具类
 * 
 * @author tony
 * @create @date Jan 14, 2012-3:16:15 PM
 * @comment
 */
public class ByteUtils
{

	/**
	 * 将给定的byte数组转换成int
	 * 
	 * @param bytes
	 * @return
	 */
	public static int byteToInt(byte[] bytes)
	{
		int len = bytes.length - 1;
		int sum = 0;
		for (int i = 0; i < bytes.length; i++)
		{
			int n = (int) (bytes[i] & 0xffff);
			n <<= (len--);
			sum += n;
		}
		return sum;
	}

	/**
	 * 将int转换成32位的字节数组
	 * 
	 * @param num
	 * @return
	 */
	public static byte[] intToByte(int num)
	{
		return intToByte(num, 32);
	}

	/**
	 * 将Int转换为指定的byteLen长度的字节数组
	 * 
	 * @param num
	 * @param byteLen
	 * @return
	 */
	public static byte[] intToByte(int num , int byteLen)
	{
		if (byteLen > 32)
			throw new RuntimeException("{ " + byteLen + " } is greater than the max bits of integer");
		return toByte(num, byteLen);
	}

	/**
	 * 将指定整数转换为长度为 byteLen的byte 数组
	 * 
	 * @param num
	 * @param byteLen
	 * @return
	 */
	private static byte[] toByte(int num , int byteLen)
	{
		byte[] result = new byte[byteLen];
		fillByteWithHighBit(result);
		if ((byteLen == 64 || byteLen == 32) && num >= 0)
		{
			result[0] &= 0x0;
		}
		if (byteToInt(result) < num)
			throw new RuntimeException("Number {" + num + "} convert to byte array need more bit.{ " + byteLen
					+ "} is less than the target byte array size");
		fillByteWithLowBit(result);
		String binaryStr = Integer.toBinaryString(num);
		int count = 0;
		if (!binaryStr.trim().equals(""))
		{
			if (binaryStr.length() < byteLen)
			{
				count += (byteLen - binaryStr.length());
			}
			fillBit(binaryStr, result, count);
		}
		else
		{
			throw new RuntimeException("Number format error");
		}
		return result;
	}

	/**
	 * 填充Bit位
	 * 
	 * @param bitString
	 * @param dest
	 */
	private static void fillBit(String bitString , byte[] dest , int count)
	{
		for (Character c : bitString.toCharArray())
		{
			dest[count] |= Integer.parseInt(c.toString());
			count++;
		}
	}

	/**
	 * 使用高位1填充一个byte数组
	 * 
	 * @param bytes
	 */
	public static void fillByteWithHighBit(byte[] bytes)
	{
		for (int i = 0; i < bytes.length; i++)
		{
			bytes[i] |= 0x1;
		}
	}

	/**
	 * 使用地位0填充一个byte数组
	 * 
	 * @param bytes
	 */
	public static void fillByteWithLowBit(byte[] bytes)
	{
		for (int i = 0; i < bytes.length; i++)
		{
			bytes[i] &= 0x0;
		}
	}

	public static void printByte(byte[] b)
	{
		for (int i = 0; i < b.length; i++)
		{
			System.out.print(b[i]);
		}
		System.out.println();
	}

	public static int copyToDestByte(byte[] from , byte[] to , int startIndex)
	{
		for (int i = 0; i < from.length; i++)
		{
			to[startIndex++] = from[i];
		}
		return startIndex;
	}

}
